<template>
  <Card
    title="查看邮件"
    v-loading="loading"
    :bordered="false"
    :head-style="{ padding: '0' }"
    :body-style="{ padding: '10px 0' }"
  >
    <div class="flex flex-col gap-2">
      <div style="background-color: #e7eff6" class="flex justify-start gap-2 p-8px mb-2">
        <Button type="primary" @click="handleReturn">
          <template #icon>
            <RollbackOutlined />
          </template>
          返回
        </Button>
        <Button type="primary" @click="handleRefresh">
          <template #icon>
            <RedoOutlined />
          </template>
          刷新
        </Button>
        <Button type="primary" @click="handleReply">
          <template #icon>
            <Icon icon="clarity:chat-bubble-line" />
          </template>
          回复
        </Button>
        <Button @click="handleDelete">
          <template #icon> <DeleteOutlined style="color: red" /> </template>
          删除
        </Button>
        <Button type="primary" @click="handleTransmit">
          <template #icon> <SendOutlined /> </template>
          转发
        </Button>
        <Button @click="handleDeleteBatch" v-if="type != 'garbageBinbox'">
          <template #icon>
            <DeleteOutlined style="color: red" />
          </template>
          删除会话
        </Button>
        <Button>
          <Checkbox v-model:checked="isSessionMode" @change="handleIsSessionMode"
            >会话模式</Checkbox
          >
        </Button>
      </div>
      <div
        class="flex flex-col gap-2 p-2"
        style="background-color: #efefef; border-bottom: 1px solid #acdcdc"
      >
        <div class="flex gap-2">
          <div>主题：</div>
          <div>{{ model.title }}</div>
        </div>
        <div class="flex gap-2">
          <div>发件人：</div>
          <div>{{ model.senderRealName }}</div>
        </div>
        <div class="flex gap-2">
          <div>收件人：</div>
          <div>{{ model.realNameJs }}</div>
        </div>
        <div class="flex gap-2" v-if="model.realNameCs && model.realNameCs.length > 0">
          <div>抄送：</div>
          <div>{{ model.realNameCs }}</div>
        </div>
        <div class="flex gap-2" v-if="model.realNameMs && model.realNameMs.length > 0">
          <div>密送：</div>
          <div>{{ model.realNameMs }}</div>
        </div>
        <div class="flex gap-2">
          <div>时间：</div>
          <div>{{ model.rq }}</div>
        </div>
      </div>
      <div class="flex flex-col gap-2 p-2">
        <template v-if="isSessionMode">
          <div v-for="(item, index) in sessionList" :key="index">
            <div class="flex gap-2 items-center">
              <div>{{ item.senderRealName }}</div>
              <div>{{ item.sendTime }}</div>
              <Button
                type="link"
                v-if="item.receiver == userInfo.name"
                @click="handleSessionListDelete(item.id)"
                >删除</Button
              >
              <Button type="link" @click="handleSessionListTransmit(item)">转发</Button>
            </div>
            <div class="flex flex-col gap-2 session-list-content">
              <div class="text-bold">【{{ item.title }}】</div>
              <div v-html="item.content" v-if="item.content"></div>
              <div v-if="item.attachments && item.attachments.length">
                <div v-for="(el, eli) in item.attachments" :key="eli">
                  <a @click="handleDonwload(el)">{{ el.name }}</a>
                  <a @click="handlePreview(el)" title="预览" v-if="el.previewUrl" class="ml-3"
                    ><EyeOutlined style="color: rgba(28, 106, 235, 1)"
                  /></a>
                </div>
              </div>
            </div>
          </div>
        </template>
        <template v-else>
          <div>
            <div v-if="model.content" v-html="model.content"></div>
            <div class="mt-5" v-if="model.attachments && model.attachments.length">
              <div v-for="(item, index) in model.attachments" :key="index">
                <a @click="handleDonwload(item)">{{ item.name }}</a>
                <a @click="handlePreview(item)" title="预览" v-if="item.previewUrl" class="ml-3"
                  ><EyeOutlined style="color: rgba(28, 106, 235, 1)"
                /></a>
              </div>
            </div>
          </div>
        </template>
      </div>
      <template v-if="isShowEditInfo">
        <div>
          <Tinymce :showImageUpload="false" v-model="dataRef.content" />
        </div>
        <div>
          附件：<Upload :file-list="fileList" :before-upload="beforeUpload" @remove="handleRemove">
            <Button>
              <upload-outlined />
              上传文件
            </Button>
          </Upload>
        </div>
        <div class="text-center">
          <Button type="primary" @click="handleSubmit">回复</Button>
        </div>
      </template>
    </div>
  </Card>
</template>
<script lang="ts" setup>
  import { ref, onMounted, computed, nextTick, h } from 'vue';
  import { Card, Checkbox, Upload, UploadProps, Button } from 'ant-design-vue';
  import { Tinymce } from '/@/components/Tinymce/index';
  import {
    RedoOutlined,
    DeleteOutlined,
    SendOutlined,
    RollbackOutlined,
    UploadOutlined,
    EyeOutlined,
  } from '@ant-design/icons-vue';
  import Icon from '/@/components/Icon';
  import {
    getMessage_oaShow,
    getMessage_oaReply,
    getMessage_oaListChat,
    getMessage_oaDelToDustbin,
    getMessage_oaDel,
    getMessage_oaSendReceipt,
    getMessage_oaDelChat,
  } from '/@/api/email/email';
  import { downloadByUrl } from '/@/utils/file/download';
  import { useUserStore } from '/@/store/modules/user';
  import { useMessage } from '/@/hooks/web/useMessage';

  const props = defineProps({
    type: {
      type: String,
      default: '',
    },
    currentRecord: {
      type: Object,
      default: () => {
        return {};
      },
    },
    isDraft: {
      type: Boolean,
      default: false,
    },
  });
  const emit = defineEmits(['handle-return', 'handle-transmit', 'handle-reply']);
  const { createMessage, createConfirm } = useMessage();
  const userStore = useUserStore();
  const serverInfo = userStore.getServerInfo;
  const userInfo = userStore.getUserInfo;
  const loading = ref(false);
  const isSessionMode = ref(false);
  const isShowEditInfo = computed(() => props.type != 'garbageBinbox');
  const dataRef = ref({
    content: '',
  });
  const model = ref<Recordable>({});
  const sessionList = ref<Recordable[]>([]);
  //返回
  const handleReturn = () => {
    emit('handle-return');
  };
  //刷新
  const handleRefresh = () => {
    fetch();
    handleClear();
  };
  //回复
  const handleReply = () => {
    emit('handle-reply');
  };
  //删除
  const handleDelete = async () => {
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '确定删除吗？'),
      onOk: async () => {
        try {
          loading.value = true;
          if (model.value.dustbin) {
            await getMessage_oaDel({ ids: props.currentRecord.id });
          } else {
            await getMessage_oaDelToDustbin({ ids: props.currentRecord.id });
          }
          createMessage.success('操作成功');
          loading.value = false;
          // handleRefresh();
          handleReturn();
        } catch (error) {
        } finally {
          loading.value = false;
        }
      },
    });
  };
  //转发
  const handleTransmit = () => {
    emit('handle-transmit', props.currentRecord);
  };
  //删除会话
  const handleDeleteBatch = () => {
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '您确定删除么？'),
      onOk: async () => {
        try {
          loading.value = true;
          await getMessage_oaDelChat({ ids: props.currentRecord.id });
          handleRefresh();
        } catch (error) {
        } finally {
          loading.value = false;
        }
      },
    });
  };
  //会话模式
  const handleIsSessionMode = (e) => {
    const { checked } = e.target;
    console.log('checked', checked);
  };

  //删除会话单条记录
  const handleSessionListDelete = async (id) => {
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '您确定删除么？'),
      onOk: async () => {
        try {
          loading.value = true;
          await getMessage_oaDelToDustbin({ ids: id });
          createMessage.success('操作成功');
          loading.value = false;
          handleRefresh();
        } catch (error) {
        } finally {
          loading.value = false;
        }
      },
    });
  };
  //转发会话单条记录
  const handleSessionListTransmit = (record) => {
    emit('handle-transmit', record);
  };
  //回执
  const handleReceiptState = () => {
    createConfirm({
      iconType: 'info',
      title: () => h('span', '消息发送者需要回执，现在就发送回执么？'),
      onOk: async () => {
        try {
          loading.value = true;
          await getMessage_oaSendReceipt({ id: props.currentRecord.id });
          // handleRefresh();
        } catch (error) {
          console.log(error);
        } finally {
          loading.value = false;
        }
      },
    });
  };

  const fileList = ref<UploadProps['fileList']>([]);
  const handleRemove: UploadProps['onRemove'] = (file) => {
    const index = fileList.value.indexOf(file);
    const newFileList = fileList.value.slice();
    newFileList.splice(index, 1);
    fileList.value = newFileList;
  };
  const beforeUpload: UploadProps['beforeUpload'] = (file) => {
    fileList.value = [...fileList.value, file];
    return false;
  };

  //确定
  const handleSubmit = async () => {
    try {
      console.log('dataRef', dataRef.value);
      console.log('props.currentRecord', props.currentRecord);
      if (!dataRef.value.content) {
        createMessage.warning('请输入内容');
        return;
      }
      const params = {
        title: props.currentRecord.title,
        id: props.currentRecord.id,
        receiver: props.currentRecord.sender,
        isDraft: props.isDraft,
        userRealName: props.currentRecord.senderRealName,
        att1: '',
        content: dataRef.value.content,
      };
      console.log('params', params);

      fileList.value?.forEach((item, index) => {
        params[`att${index + 1}`] = item;
      });
      const formata = new FormData();
      for (let v in params) {
        formata.append(v, params[v]);
      }
      loading.value = true;
      await getMessage_oaReply(formata);
      loading.value = false;
      handleRefresh();
    } catch (error) {
    } finally {
      loading.value = false;
    }
  };

  const handleClear = () => {
    dataRef.value.content = '';
    fileList.value = [];
  };

  //下载
  const handleDonwload = (record) => {
    const path = record.visualPath + '/' + record.diskName;
    const fileName = record.name;
    const url = path
      ? serverInfo.rootPath + (path && path.startsWith('/') ? path : `/${path}`)
      : '';
    downloadByUrl({ url, fileName });
  };

  const handlePreview = computed(() => (record: any) => {
    const rootPath = serverInfo.rootPath;
    window.open(rootPath + '/' + record.previewUrl);
  });

  //获取会话列表
  const getMessage_oaListChatList = async () => {
    try {
      const res = await getMessage_oaListChat({
        receiver: props.currentRecord.receiver,
        sender: props.currentRecord.sender,
      });
      sessionList.value = res || [];
    } catch (error) {}
  };

  const fetch = () => {
    nextTick(async () => {
      if (!props.currentRecord.id) return;
      loading.value = true;
      const res = await getMessage_oaShow({ id: props.currentRecord.id });
      model.value = res;
      await getMessage_oaListChatList();
      loading.value = false;
      //根据条件判断回执
      if (res.receiptState == 1) {
        handleReceiptState();
      }
    });
  };
  onMounted(fetch);
</script>
<style lang="less" scoped>
  .session-list-content {
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;
    border-radius: 10px;
    position: relative;
    padding: 8px;
    background-color: #f3f3f3;
    border: 1px solid #92c64a;
    word-wrap: break-word;
    line-height: 25px;
    border: 1px solid #d5d5d5;
  }
  :deep(.ant-card-head-title) {
    padding: 8px 8px 0;
  }
</style>
